import React, { PureComponent } from 'react';
import classNames from 'classnames';
import { Menu, Icon, Form, Spin } from 'antd';
import { connect } from 'dva';
import Link from 'umi/link';
import { urlToList } from '../_utils/pathTools';
import { getMenuMatches } from './SiderMenuUtils';
import { isUrl } from '@/utils/utils';
import styles from './index.less';
import IconFont from '@/components/IconFont';
import axios from 'axios';
import qs from 'qs';
import bar from '@/assets/js/bar.png';

const { SubMenu } = Menu;

// Allow menu.js config icon as string or ReactNode
//   icon: 'setting',
//   icon: 'icon-geren' #For Iconfont ,
//   icon: 'http://demo.com/icon.png',
//   icon: <Icon type="setting" />,
const getIcon = icon => {
  if (typeof icon === 'string') {
    if (isUrl(icon)) {
      return <Icon component={() => <img src={icon} alt="icon" className={styles.icon} />} />;
    }
    if (icon.startsWith('icon-')) {
      return <IconFont type={icon} />;
    }
    return <Icon type={icon} />;
  }
  return icon;
};

class BaseMenu extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      menuData: this.props.menuData,
      currentUser: this.props.currentUser,
      login: false,
    };
  }

  /**
   * 获得菜单子节点
   * @memberof SiderMenu
   */

  componentDidMount() {
    this.getmenus();
  }
  // --- 菜单开始 ---

  // 根据登录用户的id查询功能菜单
  getmenusByUserId = menuData => {
    const { dispatch } = this.props;
    const { currentUser } = this.state;

    const robotName =
      window.localStorage.getItem('robotName') == undefined
        ? ''
        : window.localStorage.getItem('robotName');
    console.log(robotName);
    if (robotName) {
      let objurl = {
        name: robotName,
        classType: 'overv',
        path: '/overviewRobotsa',
        component: './overviewRobots/home/Index',
        icon: bar,
        hideInMenu: false,
        isAuth: false,
      };
      let result = menuData.every(this.isBigEnough);
      console.log(result);
      if (result) {
        menuData.splice(2, 0, objurl);
      } else {
        menuData.splice(2, 1);
      }
      this.setState({ login: false });
    }
  };

  isBigEnough = element => {
    let robotNames =
      window.localStorage.getItem('robotName') == undefined
        ? ''
        : window.localStorage.getItem('robotName');
    return element.name !== robotNames;
  };

  localeArr = (arrylist, menuData) => {
    // console.log(arrylist, menuData);
    menuData.map((item, index) => {
      item.isAuth = false;
      arrylist.map(iteme => {
        if (iteme === item.name) {
          item.isAuth = true;
        }
      });
      if (item.children) {
        this.localeArr(arrylist, item.children);
      } else {
        item.isAuth = false;
        arrylist.map(items => {
          if (items === item.name) {
            // console.log(item);
            item.isAuth = true;
          }
        });
      }
    });
    this.fixMenuData(menuData);
  };

  // 未选中机器人登录
  localeArrno = menuData => {
    // console.log(arrylist, menuData);
    let arrylist = ['首页', '机器人总览', '系统管理'];
    menuData.map((item, index) => {
      item.isAuth = false;
      arrylist.map(iteme => {
        if (iteme === item.name) {
          item.isAuth = true;
        }
      });
    });
    this.fixMenuData(menuData);
  };

  fixMenuData = menuData => {
    for (let i of menuData) {
      if (i.iconIsCustom) {
        i.icon = robotDeployUrl + i.icon;
      }
    }
    this.setState({
      menuData,
    });
  };

  getmenus = () => {
    // let Menus =
    //   window.localStorage.getItem('Menus') == undefined ? '' : window.localStorage.getItem('Menus');
    // Menus = Menus.split(',');
    // console.log(Menus);
    this.setState({ login: true });
    let { menuData } = this.state;
    let { currentUser } = this.props;
    let arrylist = [];
    let uid =
      window.localStorage.getItem('uid') == undefined ? '' : window.localStorage.getItem('uid');
    const robotId =
      window.localStorage.getItem('robotId') == undefined
        ? ''
        : window.localStorage.getItem('robotId');
    const token =
      JSON.parse(window.localStorage.getItem('currentUser')) == undefined
        ? ''
        : JSON.parse(window.localStorage.getItem('currentUser')).token;
    console.log('缓存uid', uid);
    let api = '/cloud/new/sys/getmenusByUserId'; // 一般权限
    let apia = '/cloud/new/robot/getRobotList'; // 机器人列表
    let apib = '/cloud/new/collabora/getcoopRotbotMenus'; // 协作开发机器人列表
    const obj = { userId: uid };
    const obja = { userId: uid, robotId: robotId };
    const params = qs.stringify(obj);
    const paramsa = qs.stringify(obja);
    const newUrl = api + '?' + params;
    const newUrla = apia + '?' + params;
    const newUrlb = apib + '?' + paramsa;

    const headData = { 'Content-Type': 'application/json', token: token, robotId: robotId };
    console.log(robotId);

    // 获取机器人列表
    let coopertion = [];
    let ownRobot = [];
    axios.get(newUrla, { headers: headData }).then(res => {
      if (res.data.data) {
        coopertion = res.data.data.coopertion ? res.data.data.coopertion : [];
        ownRobot = res.data.data.ownRobot ? res.data.data.ownRobot : [];
      }

      console.log(coopertion);
      if (coopertion.length) {
        // 判断渲染协作开发菜单还是一般开发菜单
        let current = coopertion.some(items => {
          return items.id === robotId;
        });
        console.log(current);
        if (current) {
          // 协作开发
          // console.log('协作开发', item.id, robotId, currentUser);
          axios.get(newUrlb, { headers: headData }).then(res => {
            let a = res.data.data === undefined ? [] : res.data.data;
            console.log('协作开发机器人权限', res.data.data, a);
            arrylist = ['11', ...[...a,'问答详细统计','问答记录',]];
            // arrylist = ['11', ...a];
            setTimeout(() => {
              this.getmenusByUserId(menuData);
              this.setState({ name: 1 });
            }, 1);
            if (arrylist) {
              if (arrylist.length) {
                // 用户权限

                if (robotId === '1') {
                  // 未选中机器人登录
                  console.log('未选中机器人登录');
                  this.localeArrno(menuData);
                } else {
                  this.localeArr(arrylist, menuData);
                }
              }
            }
          });
        } else {
          // 一般权限
          // console.log('我的创建', item.id, robotId, currentUser);
          axios.get(newUrl, { headers: headData }).then(res => {
            console.log('我的创建机器人', res);
            arrylist = ['11', ...[...res.data.data,'问答详细统计','问答记录',]];
            setTimeout(() => {
              this.getmenusByUserId(menuData);
              this.setState({ name: 1 });
            }, 1);
            if (arrylist) {
              if (arrylist.length) {
                // 用户权限

                if (robotId === '1') {
                  // 未选中机器人登录
                  console.log('未选中机器人登录');
                  this.localeArrno(menuData);
                } else {
                  this.localeArr(arrylist, menuData);
                }
              }
            }
          });
        }

        // coopertion.map(item => {
        //   const robotme =
        //     window.localStorage.getItem('robotName') == undefined
        //       ? ''
        //       : window.localStorage.getItem('robotName');

        //   if (item.id === robotId) {
        //     // 协作开发机器人
        //     console.log('协作开发',item.id,robotId,currentUser)
        //     axios.get(newUrlb, { headers: headData }).then(res => {
        //       let a = res.data.data === undefined ?[]:res.data.data
        //       console.log('协作开发机器人权限', res.data.data,a);
        //       arrylist = ['11', ...a];
        //       setTimeout(() => {
        //         this.getmenusByUserId(menuData);
        //         this.setState({ name: 1 });
        //       }, 1);
        //       if (arrylist) {
        //         if (arrylist.length) {
        //           // 用户权限

        //           if(robotId==='1'){
        //             // 未选中机器人登录
        //             console.log('未选中机器人登录')
        //              this.localeArrno(menuData)
        //            }else{
        //             this.localeArr(arrylist, menuData);
        //            }

        //         }
        //       }
        //     });
        //   } else {
        //     console.log('我的创建',item.id,robotId,currentUser)
        //     axios.get(newUrl, { headers: headData }).then(res => {
        //       console.log('我的创建机器人',res);
        //       arrylist = ['11', ...res.data.data];
        //       setTimeout(() => {
        //         this.getmenusByUserId(menuData);
        //         this.setState({ name: 1 });
        //       }, 1);
        //       if (arrylist) {
        //         if (arrylist.length) {
        //           // 用户权限

        //           if(robotId==='1'){
        //             // 未选中机器人登录
        //             console.log('未选中机器人登录')
        //              this.localeArrno(menuData)
        //            }else{
        //             this.localeArr(arrylist, menuData);
        //            }
        //         }
        //       }
        //     });
        //   }
        // });
      } else {
        // 一般权限
        console.log('我的创建', robotId, currentUser);
        axios.get(newUrl, { headers: headData }).then(res => {
          console.log('我的创建机器人', res);
          if(res.data.code === 401){
            localStorage.clear();
            window.g_app._store.dispatch({
              type: 'login/logout',
            });
            return;
          }
          arrylist = ['11', ...[...res.data.data,'问答详细统计','问答记录',]];
          setTimeout(() => {
            this.getmenusByUserId(menuData);
            this.setState({ name: 1 });
          }, 1);
          if (arrylist) {
            if (arrylist.length) {
              // 用户权限
              if (robotId === '1') {
                // 未选中机器人登录
                console.log('未选中机器人登录');
                this.localeArrno(menuData);
              } else {
                this.localeArr(arrylist, menuData);
              }
            }
          }
        });
      }
    });
  };

  // ---菜单模块结束 ---

  getNavMenuItems = menusData => {
    if (!menusData) {
      return [];
    }
    return menusData
      .filter(item => item.name && !item.hideInMenu)
      .map(item => this.getSubMenuOrItem(item))
      .filter(item => item);
  };

  // Get the currently selected menu
  getSelectedMenuKeys = pathname => {
    const { flatMenuKeys } = this.props;
    return urlToList(pathname).map(itemPath => getMenuMatches(flatMenuKeys, itemPath).pop());
  };

  /**
   * get SubMenu or Item
   */
  getSubMenuOrItem = item => {
    // doc: add hideChildrenInMenu
    if (item.children && !item.hideChildrenInMenu && item.children.some(child => child.name)) {
      const { name, classType } = item;
      return (
        <SubMenu
          title={
            item.icon ? (
              <div className={styles.menuFirst + '  ' + classType}>
                <span>
                  {getIcon(item.icon)}
                  <span>{name}</span>
                </span>
              </div>
            ) : (
              name
            )
          }
          disabled={!item.isAuth}
          key={item.path}
        >
          {this.getNavMenuItems(item.children)}
        </SubMenu>
      );
    }
    return !item.isAuth ? (
      <Menu.Item key={item.path} className={styles.disabled + '  ' + item.classType} disabled>
        {this.getMenuItemPath(item)}
      </Menu.Item>
    ) : (
      <Menu.Item key={item.path}>{this.getMenuItemPath(item)}</Menu.Item>
    );
  };

  /**
   * 判断是否是http链接.返回 Link 或 a
   * Judge whether it is http link.return a or Link
   * @memberof SiderMenu
   */
  getMenuItemPath = item => {
    const { name } = item;
    const itemPath = this.conversionPath(item.path);
    const icon = getIcon(item.icon);
    const { target, classType } = item;
    // Is it a http link
    if (/^https?:\/\//.test(itemPath)) {
      return (
        <a href={itemPath} target={target} className={classType}>
          {icon}
          <span>{name}</span>
        </a>
      );
    }
    const { location, isMobile, onCollapse } = this.props;
    return (
      <Link
        to={itemPath}
        target={target}
        replace={itemPath === location.pathname}
        className={styles.menuFirst + ' ' + classType}
        onClick={
          isMobile
            ? () => {
                onCollapse(true);
              }
            : undefined
        }
      >
        {icon}
        <span style={classType === 'overv' ? { color: ' #37B7DC' } : {}}>{name}</span>
      </Link>
    );
  };

  conversionPath = path => {
    if (path && path.indexOf('http') === 0) {
      return path;
    }
    return `/${path || ''}`.replace(/\/+/g, '/');
  };

  render() {
    const {
      openKeys,
      theme,
      mode,
      location: { pathname },
      className,
      collapsed,
    } = this.props;
    // if pathname can't match, use the nearest parent's key
    let selectedKeys = this.getSelectedMenuKeys(pathname);
    if (!selectedKeys.length && openKeys) {
      selectedKeys = [openKeys[openKeys.length - 1]];
    }
    let props = {};
    if (openKeys && !collapsed) {
      props = {
        openKeys: openKeys.length === 0 ? [...selectedKeys] : openKeys,
      };
    }
    const { handleOpenChange, style } = this.props;
    const { currentUser, menuData } = this.state;

    const cls = classNames(className, {
      'top-nav-menu': mode === 'horizontal',
    });

    return (
      // <Spin spinning={this.state.login}>
      <Menu
        key="Menu"
        mode={mode}
        theme={theme}
        onOpenChange={handleOpenChange}
        selectedKeys={selectedKeys}
        style={style}
        className={cls}
        {...props}
      >
        {this.getNavMenuItems(menuData)}
      </Menu>
      // </Spin>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(BaseMenu));
